package com.qingcloud.adminbackend.controller;


import com.qingcloud.adminbackend.base.AjaxResult;
import com.qingcloud.adminbackend.constant.WamingConstant;
import com.qingcloud.adminbackend.entity.sysorg.*;
import com.qingcloud.adminbackend.entity.sysorg.*;
import com.qingcloud.adminbackend.entity.user.SysUser;
import com.qingcloud.adminbackend.service.ISysOrgService;
import com.qingcloud.adminbackend.service.ISysUserService;
import com.qingcloud.adminbackend.utils.CookieUtil;
import com.qingcloud.base.annotation.LoginUser;
import com.qingcloud.base.constant.SecurityConstants;
import com.qingcloud.base.remote.pojo.LoginUserDTO;
import io.swagger.annotations.ApiImplicitParam;
import io.swagger.annotations.ApiImplicitParams;
import io.swagger.annotations.ApiOperation;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.util.StringUtils;
import org.springframework.web.bind.annotation.*;

import javax.annotation.Resource;
import javax.servlet.http.HttpServletRequest;
import java.util.List;

/**
 * <p>
 * 客户表 前端控制器
 * </p>
 *
 * @author liyuhong
 * @since 2018-11-15
 */
@RestController
@RequestMapping("/sys-org")
public class OrgController {

    @Resource
    private ISysOrgService sysOrgService;

    @Resource
    private ISysUserService sysUserService;

    @ApiOperation(value = "查询列表Api", notes = "查询列表：\n" +
            "         \n" +
            "\t(1）默认查询/ 加条件查询\n" +
            "\t\n" +
            "\t（2） 蛙鸣客户 /客户-管理员 不同身份处理不一样。\n" +
            "\n" +
            "\t　\n" +
            "\t\t判断用户为非蛙鸣用户并且客户类型为一级客户：\n" +
            "\t \n" +
            "\t\t查询sys_user_org_mgr，找出当前用户所有记录，关联用户表(sys_usesr)，客户表(sys_org)。\n" +
            "\t \n" +
            "\t \n" +
            "\t\t判断是查看还是编辑权限：\n" +
            "\t \n" +
            "\t\t判断是否有添加分支机构：\n" +
            "\t \n" +
            "\t\t判断是否有订单管理；\n" +
            "\t \n" +
            "\t\t判断是否有可用设备组管理：\n" +
            "\t \n" +
            "\t\t判断是否有删除分支机构：\n" +
            "\t \n" +
            "\t(3） 系统管理员完全管理权限-特殊处理\n" +
            "\t  \n" +
            "\t\t所有功能功能都能操作\n" +
            "\n", response = SysOrgBO.class)
    @PostMapping("/findSysOrgList")
    public AjaxResult findSysOrgList(@RequestBody SysOrgDTO sysOrgDTO, HttpServletRequest request) {
        sysOrgDTO.setUserId(CookieUtil.getUserId(request));
        boolean isAdmin = CookieUtil.isAdmin(request);
        if (!StringUtils.isEmpty(sysOrgDTO.getUserId())) {
            SysUser user = sysUserService.getById(CookieUtil.getUserId(request));
            if (user.getAdminFlag() == 1) {
                isAdmin = true;
            }
            int userType = user.getUserType();
            sysOrgDTO.setUserType(userType);
        }
        sysOrgDTO.setAdmin(isAdmin);
        return new AjaxResult(WamingConstant.SUCCESS, null, sysOrgService.findSysOrgList(sysOrgDTO, isAdmin));
    }

    @PostMapping("/setSysOrg")
    public AjaxResult setSysOrg(@RequestBody SysOrg sysOrg, HttpServletRequest request) {
        boolean isAdmin = CookieUtil.isAdmin(request);
        String userId = CookieUtil.getUserId(request);
        if(!isAdmin) {
            if (!StringUtils.isEmpty(userId)) {
                SysUser user = sysUserService.getById(userId);
                if (user.getAdminFlag() == 1) {
                    isAdmin = true;
                }
            }
        }
        sysOrg.setCreateBy(userId);
        return sysOrgService.setSysOrg(sysOrg,isAdmin);
    }

    @ApiOperation(value = "删除客户Api", notes = "删除客户Api")
    @PostMapping("/deleteSysOrg")
    public AjaxResult deleteSysOrg(@RequestBody List<String> ids) {
        return sysOrgService.deleteSysOrg(ids);
    }

    @ApiOperation(value = "查询详情Api", notes = "基本信息Logo可用功能（上级功能），已经勾选功能（sys_org_function）")
    @ApiImplicitParams({@ApiImplicitParam(name = "id", value = "客户Id", defaultValue = "1", required = false, dataType = "String", paramType =
            "query")})
    @GetMapping("/findSysOrgById")
    public AjaxResult findSysOrgById(String id) {
        return new AjaxResult(WamingConstant.SUCCESS, null, sysOrgService.findSysOrgById(id));
    }

    @ApiOperation(value = "客户关联的订单Api", notes = "该客户已经关联的订单；订单表：sys_order")
    @PostMapping("/findOrgOrderByOrgId")
    public AjaxResult findOrgOrderByOrgId(@RequestBody SysOrgOrderDTO sysOrgOrderDTO) {
        return new AjaxResult(WamingConstant.SUCCESS, null, sysOrgService.findOrgOrderByOrgId(sysOrgOrderDTO));
    }

    /**
     * 当前登录用户的客户管理权限范围内的有写权限的组织，并且是被授权用户的所在客户内部的客户或分支机构。
     *
     * @param request
     * @return
     */
    @ApiOperation(value = "当前登录用户的客户管理权限范围内的有写权限的组织，并且是被授权用户的所在客户内部的客户或分支机构。",
            notes = "当前登录用户的客户管理权限范围内的有写权限的组织，并且是被授权用户的所在客户内部的客户或分支机构。")
    @ApiImplicitParams({
            @ApiImplicitParam(name = "orgId", value = "被授权用户的所在客户ID", required = true, dataType = "string", paramType = "path")
    })
    @GetMapping("/findOrgByUserOrg/{orgId}")
    public AjaxResult findOrgByUserOrg(@PathVariable("orgId") String orgId, HttpServletRequest request, @LoginUser LoginUserDTO loginUserDTO) {
        boolean isAdmin = loginUserDTO.getIsAdmin()==1?true:false;
        String userId = loginUserDTO.getUserId();
        return new AjaxResult(WamingConstant.SUCCESS, "", sysOrgService.findOrgByUserOrg(orgId, userId, isAdmin));
    }

    @ApiOperation(value = "查询登录用户可管理客户以及子客户(只有写权限)", notes = "查询登录用户可管理客户以及子客户")
    @ApiImplicitParams({
            @ApiImplicitParam(name = "businessType", value = "1-网格化，2-健康云", dataType = "string", paramType = "query")
    })
    @PostMapping(value = "/findOrgListByLoginUser")
    public AjaxResult findOrgList(String businessType, HttpServletRequest request,@LoginUser LoginUserDTO loginUserDTO) {
        boolean isAdmin = CookieUtil.isAdmin(request);
        String userId = loginUserDTO.getUserId();
        return new AjaxResult(WamingConstant.SUCCESS, "", sysOrgService.findOrgList(businessType, userId, isAdmin));
    }

    @ApiOperation(value = "查询登录用户可管理可查看的客户以及子客户(读写权限)", notes = "查询登录用户可管理可查看的客户以及子客户")
    @PostMapping(value = "/getOrgTreeByLoginUser")
    public AjaxResult getOrgTreeByLoginUser(String businessType, HttpServletRequest request,@LoginUser LoginUserDTO loginUserDTO) {
        String userId = loginUserDTO.getUserId();
        boolean isAdmin = loginUserDTO.getIsAdmin()==1?true:false;
        return new AjaxResult(WamingConstant.SUCCESS, "", sysOrgService.getOrgTreeByLoginUser(businessType, userId, isAdmin));
    }

    @ApiOperation(value = "查询登录用户可管理客户/订单/设备池", notes = "查询登录用户可管理客户/订单/设备池",response = SysUserMgrDTO.class)
    @ApiImplicitParams({
            @ApiImplicitParam(name = "parameter", value = "搜索参数", dataType = "string", paramType = "query"),
            @ApiImplicitParam(name = "businessType", value = "1-网格化，2-健康云", dataType = "string", paramType = "query")
    })
    @GetMapping(value = "/findOrgToOrderToPool")
    public AjaxResult findOrgToOrderToPool(String businessType,String parameter,HttpServletRequest request) {
        boolean isAdmin = CookieUtil.isAdmin(request);
        String userId = CookieUtil.getUserId(request);
        return new AjaxResult(WamingConstant.SUCCESS, "", sysOrgService.findOrgToOrderToPool(userId, isAdmin,parameter,businessType));
    }

    @ApiOperation(value = "获取业务类型", notes = "")
    @GetMapping("/getBusinessType")
    public AjaxResult getBusinessType(@LoginUser LoginUserDTO loginUserDTO) {
        if(loginUserDTO==null || loginUserDTO.getUserId()==null) {
            return AjaxResult.fail("无法获取用户信息");
        }

        return new AjaxResult(WamingConstant.SUCCESS, null, sysOrgService.getBusinessType(loginUserDTO.getUserId()));
    }

    @ApiOperation(value = "获取用户身份", notes = "")
    @ApiImplicitParams({
            @ApiImplicitParam(name = "businessType", value = "业务类型", dataType = "string", paramType = "query")
    })
    @GetMapping("/getRoleByBusinessType")
    public AjaxResult getRoleByBusinessType(String businessType, @LoginUser LoginUserDTO loginUserDTO) {

        return new AjaxResult(WamingConstant.SUCCESS, null, sysOrgService.getRoleByBusinessType(businessType, loginUserDTO.getUserId()));
    }

    @ApiOperation(value = "获取授权用户业务种类和角色", notes = "")
    @ApiImplicitParams({
            @ApiImplicitParam(name = "userId", value = "授权用户的id", dataType = "string", paramType = "query")
    })
    @GetMapping("/getRoleBusinessTypeByAuthorUser")
    public AjaxResult getRoleBusinessTypeByAuthorUser(String userId) {
        return new AjaxResult(WamingConstant.SUCCESS, null, sysOrgService.getRoleBusinessTypeByAuthorUser(userId));
    }

    @ApiOperation(value = "查询登录用户可管理可查看的客户以及用户列表", notes = "查询登录用户可管理可查看的客户以及用户列表")
    @PostMapping(value = "/getOrgUserTree")
    public AjaxResult getOrgUserTree(HttpServletRequest request) {
        String userId = CookieUtil.getUserId(request);
        return new AjaxResult(WamingConstant.SUCCESS, "", sysOrgService.getOrgUserTree(userId));
    }
}

